package com.qf.air.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.qf.air.constants.AirConstants;
import com.qf.air.entity.User;
import com.qf.air.service.UserService;
import com.qf.air.util.JedisUtils;
import com.qf.air.util.R;
import com.qf.air.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author: 维多利加
 * @Date: 2021/3/28 16:41
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true")
public class UserController {

   @Autowired
   private UserService userService;


   @Autowired
   private JedisUtils jedisUtils;

   /**
    * # 请求路径&请求方式
    * POST 	http://localhost/user/signin
    * # 请求参数
    * username = 用户名
    * password = 密码
    */
   @PostMapping("/signin")
   public ResultVO signin(String username, String password, HttpSession session,
                          HttpServletResponse response, HttpServletRequest request) throws JsonProcessingException {
      //1. 校验参数
      if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
         System.out.println("用户名和密码均为必填项，岂能为空！");
         return R.error(222, "用户名和密码均为必填项，岂能为空！");
      }

      //2. 调用service执行登录
      User user = userService.login(username, password);

      //3. 将登录成功的用户信息存储到Session中
      //session.setAttribute("user",user);

      //登录成功,将用户信息存入redis
      String cookieValue = UUID.randomUUID().toString().replaceAll("-", "");
      Cookie cookie = new Cookie(AirConstants.USER_COOKIE, cookieValue);
      cookie.setPath("/");
      cookie.setHttpOnly(true);
      //cookie.setMaxAge(1800);

      response.addCookie(cookie);
      byte[] userKeys = SerializationUtils.serialize(AirConstants.USER_REDIS_PREFIX + cookieValue);
      byte[] users = SerializationUtils.serialize(user);
      jedisUtils.setEx(userKeys, 1800, users);
      System.out.println("\n\n\n\n\n登录成功\n\n\n\n\n");
      //4. R.ok();
      return R.ok();
   }

}
